<?php

define('PUBLIC_ROLE', 0);
define('INFLUENCER_ROLE', 1);
define('EDITOR_ROLE', 2);

class CRTUser {
	
	
	public function __construct($id=null) {
		$id = Clean::posInt($id, false, true);
		if($id) 
			$this->init($id);		
	}

	public function loggedIn() {
		return (bool)$this->id ? $this->id : false;
	}

	public function delete() {
		if(ctype_digit((string)$this->id)) {
			$db = DBs::getGISDB();
			$sql = "DELETE FROM crtusers WHERE id={$this->id}";
			$db->_Execute($sql);

			return true;

		}
	}

	public function updateRole($role) {
		$db = DBs::getGISDB();
		$role = Clean::int($role);
		
		$sql = "UPDATE ".USERS_TBL." SET role=$role WHERE id={$this->id}";
		$db->_Execute($sql);
	}

	private function init($id) {
                $db = DBs::getGISDB();
                $id = Clean::posInt($id);
		
				$sql = "SELECT * FROM ".USERS_TBL." WHERE id=$id";
        	     $res = $db->GetRow($sql);

		
                if($res) {
                        foreach($res as $k=>$r) {
                                $this->$k = $r;
                        }
                } else {
                        $this->id = false;
                }
        }

	public function add($username, $password, $role) {
		$db = DBs::getGISDB();
		$username = Clean::string($username);
		$password = Clean::string($password);
		$role = Clean::posInt($role);

		$sql = "INSERT INTO ".USERS_TBL." (username, password, role) VALUES (".$db->qstr($username).",".$db->qstr($password).", $role )";
                $db->StartTrans();

                if ($db->_Execute($sql)) {
                        $newID = $db->Insert_ID();
                }
                $db->CompleteTrans();

		return $newID;
        }

	public static function getUserByLogin($username) {
		$db = DBs::getGISDB();
		$username = Clean::string($username, false, false, true);
		if($username) {
			$sql = "SELECT username FROM ".USERS_TBL." WHERE username=".$db->qstr($username);
			return $db->GetOne($sql);
		}

		return false;
	}

	public static function getActiveUser() {
		$userId = Clean::posInt(CRTSession::get('userId'), false, true);
		if($userId) {
			$user = new CRTUser($userId);
			return $user;
		}

	}

	public static function logIn($username, $password) {
		$db = DBs::getGISDB();
		
		$sql = "SELECT * FROM ".USERS_TBL." WHERE username=".$db->qstr($username)." AND  password=".$db->qstr($password);
		$res = $db->GetRow($sql);
		if(ctype_digit((string)$res['id'])) {
			$user = new CRTUser($res['id']);
			CRTSession::set('userId', $res['id']);
			return $user;
		}

		return false;
	}

	public static function getUsers() {
		$db = DBs::getGISDB();
		$sql = "SELECT * FROM ".USERS_TBL." order by role DESC";
		return $db->GetArray($sql);
		
	}


	public static function role2Str($role) {
		$role = Clean::posInt($role);
		$ret = '';

		if($role==INFLUENCER_ROLE)
			$ret = "Influencer";
		elseif($role==EDITOR_ROLE)
			$ret = "Editor";

		return $ret;

	}
}

?>
